package com.cssy.xxkj.basic.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicMaterialsTypeDO;
import com.cssy.xxkj.basic.service.IBasicMaterialsTypeService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;
@Controller
@RequestMapping("/basic/matertype")
public class MaterialsTypeController extends BaseController<BasicMaterialsTypeDO>{
	private static final String MANAGER = "/xxkj/basic/materialsType/MaterialsTypeManager";//列表页面
	private static final String EIDT = "/xxkj/basic/materialsType/MaterialsTypeOperation";//添加、修改、显示页面
	
	@Resource(name="basicMaterialsTypeService")
	private IBasicMaterialsTypeService basicmaterTypeService;
	
	@Resource(name="syCodeService")
	private SyCodeService syCodeService;
	

	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}
	
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);//判断是否有删除标识
		hander.getWheres(scs);
		String ID=request.getParameter("ID");
		scs.addCondition("zd003ParentId", ID, SearchCondition.OP_EQUAL);
		SearchResult result=	basicmaterTypeService.findListByExample(scs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
		
	}

	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			BasicMaterialsTypeDO bd =basicmaterTypeService.findListById(id);
			model.addAttribute("parent", bd);
			model.addAttribute("flag", "add");
		}else{
			BasicMaterialsTypeDO bd =basicmaterTypeService.findListById(id);
			if(bd!=null&&bd.getId()!=null){
				BasicMaterialsTypeDO parent =basicmaterTypeService.findListById(bd.getZd003ParentId());
				model.addAttribute("parent", parent);
			}
			model.addAttribute("materialsType", bd);
			model.addAttribute("flag", "edit");
		}
		return EIDT;
	}
	
	
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			BasicMaterialsTypeDO curAP, BindingResult result, Model model)
	{
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			if (curAP.getId() != null && !"".equals(curAP.getId())) {// 修改
				basicmaterTypeService.update(curAP, SessionUtil.getUser(request));
				bodyMap.isSuccess();
				bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
				bodyMap.configWebId(curAP.getId());
			} else {// 新增
				curAP.setZd001Code(syCodeService.getCode("IT", "IT", SyCode.DATE_YYMMDD, 4));
				BasicMaterialsTypeDO cdo = basicmaterTypeService.save(curAP,SessionUtil.getUser(request));
				bodyMap.isSuccess();
				bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
				bodyMap.configWebId(cdo.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
		

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String isDelete = request.getParameter("isDelete");//标识是否是假删除
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(isDelete==null||"0".equals(isDelete)){
					basicmaterTypeService.delete(field, SessionUtil.getUser(request));
				}else{
					basicmaterTypeService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String tr=null;
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);//判断是否有删除标识
		hander.getWheres(scs);
		scs.setLimitPage(false);
		scs.setPageSize(1000);
		List<String> strlist = new ArrayList<String>();
		strlist.add("");
		strlist.add("0");
		scs.addCondition("zd003ParentId",strlist);
		List<BasicMaterialsTypeDO> list =basicmaterTypeService.findList(scs);
		if(list.size()>0){
			tr=tree(list);
			AjaxUtil.printJSonArr(response, tr);
		}else{
			AjaxUtil.printJSonArr(response, "");
		}
		
	}
	
	/**
     * 生成tree第一层数据
     **/
	private String  tree(List<BasicMaterialsTypeDO> list) throws SyBaseException {
		StringBuffer sf = new StringBuffer();
		sf.append("[");
		for (int i = 0; i < list.size(); i++) {
			sf.append("{");
			sf.append("\"text\":").append("\"").append(list.get(i).getZd002Name()).append("\"").append(",").append("\"id\":").append("\"").append(list.get(i).getId()).append("\"");
			List<BasicMaterialsTypeDO> list1 =basicmaterTypeService.findParentId(list.get(i).getId());
			if (list1 != null && list1.size() > 0) {
				sf.append(",").append("\"children\":");
				sf.append(tree(list1));
			}
			if (i == (list.size() - 1)) {
				sf.append("}");
			} else {
				sf.append("},");
			}
		}
		sf.append("]");
		return sf.toString();
	}
	@RequestMapping("/checkIsParent")
	public void checkIsParent(HttpServletRequest request,HttpServletResponse response){
		String id= request.getParameter("id");
		List<BasicMaterialsTypeDO> listMaterialType=basicmaterTypeService.findParentId(id);
		Map<String, String> outMsgMap=new HashMap<String, String>();
		if(listMaterialType.size()!=0){
			outMsgMap.put("msg", "success");
		}else{
			outMsgMap.put("msg", "fail");
		}
		OutJsonGrid out= new OutJsonGrid(outMsgMap);
		out.printJSon(response);
	}
}
